/**
 * Created by chang on 2017/2/13.
 */
const configure = require('little-man-config');
const app_config = configure.get('app');
const moment = require('moment');


const adminUser = module.exports;
adminUser.checkUserLogin = async (account, password, req) => {
    let data = await (db().admin_user.findOne({
        where: {account: account, password: helper.md5(helper.md5(password))}
    }));

    if (data) {
        req.session.admin_login_info = data;

        delete data['password'];
        return data;
    } else {
        throw new Error('用户名或者密码不正确');
    }
};

adminUser.saveUser = async (data) => {
    if (data.id) {
        let id = data.id;
        delete data['id'];

        // 校验用户
        let user = await db().admin_user.findOne({where: {account: data.account}});
        user = helper.parse(user);

        if (user && user.id !== id) {
            throw new Error('账号已存在');
        }

        return await (db().admin_user.update(data, {
            where: {
                id: id
            }
        }));
    } else {
        data.type = 1;
        data.password = helper.md5(helper.md5(app_config.default_user_password));
        data.id = helper.uuid();

        if (await (adminUser.isAccountExist(data.account))) {
            throw new Error('账号已存在');
        }

        return await (db().admin_user.create(data));
    }
};

adminUser.deleteUser = async (id) => {
    return await (db().admin_user.destroy({
        where: {id: id}
    }))
};


adminUser.queryUser = async (page, limit, keyword) => {
    let offset = (page - 1) * limit;

    let whereCase = {
        type: {$gt: 0}
    };
    if (keyword) {
        whereCase.account = {$like: '%' + keyword + '%'};
    }

    let ret = await (db().admin_user.findAndCountAll({
        offset: offset,
        limit: limit,
        order: [
            ['create_time', 'desc']
        ],
        where: whereCase
    }));

    return pager.gridWrap(ret.rows, page, limit, ret.count);
};

adminUser.isAccountExist = async (account) => {
    return await (db().admin_user.count({
        where: {
            account: account
        }
    }));
};

adminUser.resetPassword = async (id, oldpass, newpass) => {
    if (oldpass == newpass) {
        throw new Error('新密码不能和原始密码相同');
    }

    let user = await (db().admin_user.findOne({where: {id: id}}));

    if (user && user.password !== helper.md5(helper.md5(oldpass))) {
        throw new Error('原始密码不正确');
    }

    return await (db().admin_user.update({password: helper.md5(helper.md5(newpass))}, {where: {id: id}}));
};

adminUser.stat = async (user_id) => {
    let userInfo = await helper.getRow(db().admin_user, {id: user_id});

    if (!userInfo) {
        throw new Error('无效用户')
    }

    // 平台总访问量
    let obj = await helper.getRow(db().md_const_kv, {key: "TOTAL_ACCESS"});
    let todayOrderCount = await db().md_order.count({
        where: {
            create_time: {
                $gte: moment().subtract(1, 'd').endOf('days')
            },
        }
    });

    let todayOrderPrice = await db().md_order.sum('total_price', {
        where: {
            create_time: {
                $gte: moment().subtract(1, 'd').endOf('days')
            },

            status: {$in: [2, 3, 4]}
        },
    });

    return {
        totalAccess: obj.val,
        todayOrderCount: todayOrderCount,
        todayOrderPrice: todayOrderPrice,
        totalVip: await db().md_user.count(),

        myOrderCount: await db().md_order.count({where: {server_id: user_id,}}),
        myTotalPrice: await db().md_order.sum('total_price', {where: {server_id: user_id,}}),
        myTotalOnline: moment().diff(moment(userInfo.create_time), 'd')
    };
};

adminUser.statBrief = async () => {
    let todayUser = await db().md_user.count({
        where: {
            create_time: {
                $gte: moment().startOf('days')
            },
        }
    });

    let yesterdayUser = await db().md_user.count({
        where: {
            create_time: {
                $lte: moment().subtract(1, 'd').endOf('days'),
                $gte: moment().subtract(1, 'd').startOf('days')
            },
        }
    });

    let monthUser = await db().md_user.count({
        where: {
            create_time: {
                $gte: moment().startOf('months').startOf('days'),
            },
        }
    });

    let allUser = await db().md_user.count({});


    let allBrand = await db().md_brand.count({where: {type: 1}});
    let onSaling = await db().md_brand.count({where: {type: 1, is_sale: 1}}); //在售
    let onSaled = await db().md_brand.count({where: {type: 1, is_sale: 2}});  //已售

    return {
        todayUser: todayUser,
        yesterdayUser: yesterdayUser,
        monthUser: monthUser,
        allUser: allUser,

        allBrand: allBrand,
        onSaling: onSaling,
        onSaled: onSaled,

    };
};